cc.Class({
    extends: cc.Component,

    properties: {
        label: {
            default: null,
            type: cc.Label
        },
        role: cc.Prefab,
        // defaults, set visually when attaching this script to the Canvas
        text: 'Hello, World!'
    },

    // use this for initialization
    onLoad: function () {
        cc.director.setDisplayStats( true );
        this.roles  = cc.find("Canvas");

        this.frames = ["basic", "body", "footLeft", "footRight", "handLeft", "handRight", "head"];
        for(var i = 0; i < this.frames.length; i++){
            var key = this.frames[i];
            cc.loader.loadResDir(key + "/DL", cc.SpriteFrame, function (err, assets) {
                window[this+"Frame"] = assets;
                cc.log(this);
            }.bind(key));
        }

        var cloneBtn = cc.find("cloneBtn", this.node);
        if(cloneBtn)
            cloneBtn.on('click', this.clone, this);
    },
    toggleComponent: function (event, key) {
        var instance = cc.find("role", this.node) ? cc.find("role", this.node) : cc.find("roleModel", this.node);
        if(!instance) return;

        var role = instance.getComponent("role");
        if(role.isComponentExist(key))
            role.resetComponent(key);
        else
            role.setComponent(key, cc.AnimationClip.createWithSpriteFrames(window[key + "Frame"], 60).curveData);
    },

    clone: function () {
        var compnents = {
            "basic": cc.AnimationClip.createWithSpriteFrames(window["basicFrame"], 60).curveData,
            "head": cc.AnimationClip.createWithSpriteFrames(window["headFrame"], 60).curveData,
            "footRight": cc.AnimationClip.createWithSpriteFrames(window["footRightFrame"], 60).curveData,
            "footLeft": cc.AnimationClip.createWithSpriteFrames(window["footLeftFrame"], 60).curveData,
            "handRight": cc.AnimationClip.createWithSpriteFrames(window["handRightFrame"], 60).curveData,
            "handLeft": cc.AnimationClip.createWithSpriteFrames(window["handLeftFrame"], 60).curveData,
            "body": cc.AnimationClip.createWithSpriteFrames(window["bodyFrame"], 60).curveData
        };

        var instance = cc.instantiate(this.role);
        this.roles.addChild(instance);
        var role = instance.getComponent("role");
        if(role) role.init(compnents);
        instance.position = cc.p(cc.random0To1() * cc.winSize.width/2, cc.random0To1()*cc.winSize.height/2);
    },

    flip: function (event, key) {
        var instance = cc.find("role", this.node) ? cc.find("role", this.node) : cc.find("roleModel", this.node);
        if(!instance) return;

        instance.flip = !instance.flip;
        instance.runAction(cc.flipX(instance.flip));
    },

    // called every frame
    update: function (dt) {

    },
});
